﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class SplineList : MonoBehaviour {

	public GameObject[] m_splinePointsLeft;
	public GameObject[] m_splinePointsRight;
	private List<Vector3> m_pointsLeft = new List<Vector3>();
	private List<Vector3> m_pointsRight = new List<Vector3>();

	public GameObject m_leftJunction;
	public Transform m_decisionPoint;
	private bool m_decisionMade = false;
	public GameObject m_train;
	public float m_decisionDistance = 1f;

	private bool m_left;

	void Start()
	{
		m_left = m_leftJunction.activeSelf;
		CacheVectors();
	}

	void Update()
	{
		if (Vector3.SqrMagnitude(m_decisionPoint.position - m_train.transform.position) < m_decisionDistance*m_decisionDistance)
		{
			m_decisionMade = true;
		}

		if (!m_decisionMade)
		{
			m_left = m_leftJunction.activeSelf;
		}
	}

	public void CacheVectors()
	{
		m_pointsLeft.Clear();
		foreach (GameObject go in m_splinePointsLeft)
		{
			m_pointsLeft.Add(go.transform.position);
		}
		m_pointsRight.Clear();
		foreach (GameObject go in m_splinePointsRight)
		{
			m_pointsRight.Add(go.transform.position);
		}
	}

	public Vector3 GetPosition(float t)
	{
		if (m_left)
		{
			float segSize = 1f / (m_pointsLeft.Count - 1);
			int seg = (int)(t / segSize);
			if (seg >= m_pointsLeft.Count - 1)
			{
				return m_pointsLeft[m_pointsLeft.Count - 1];
			}
			float d = (t - seg * segSize) / segSize;
			return Vector3.Lerp(m_pointsLeft[seg], m_pointsLeft[seg + 1], d);
		}
		else
		{
			float segSize = 1f / (m_pointsRight.Count - 1);
			int seg = (int)(t / segSize);
			if (seg >= m_pointsRight.Count - 1)
			{
				return m_pointsRight[m_pointsRight.Count - 1];
			}
			float d = (t - seg * segSize) / segSize;
			return Vector3.Lerp(m_pointsRight[seg], m_pointsRight[seg + 1], d);
		}
	}
}
